package com.itrui.encrypted_transmission;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.StringWriter;

public class JOSNUtils {
    /**
     * 将Java对象employee序列化成为JSON格式
     * @param file
     * @return
     */
    public static String serialize(MyFile file){
        // JSON对象序列化
        String employeeJson = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            StringWriter stringWriter = new StringWriter();
            JsonGenerator jsonGenerator = new JsonFactory().createJsonGenerator(stringWriter);
            objectMapper.writeValue(jsonGenerator, file);
            jsonGenerator.close();
            employeeJson = stringWriter.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return employeeJson;
    }

    /**
     * 将JSON格式反序列化为employee对象
     * @param fileJson
     * @return
     */
    public static MyFile deserialize(String fileJson) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(fileJson, MyFile.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
